<?php

namespace Fwadmin\Model;

use Think\Model;

class AdminPurviewModel extends Model {

    protected $_validate = array(
        array('parent_id', 'require', '请选择所属父级！'),
        array('purview_name', 'require', '权限名称必须填写！'),
        array('order_id', 'require', '顺序编号必须填写！'),
        array('is_enable', array(0, 1), '请设置是否启用！', 1, 'in')
    );

    /**
     * 获取所有列表
     * @param int $parent_id 父ID
     */
    public function getList($parent_id = 0, $arr = Array()) {
        $arr1 = $this->getSub($parent_id);
        if (is_array($arr1)) {
            foreach ($arr1 as $v) {
                array_push($arr, $v);
                $arr2 = $this->getSub($v['purview_id']);
                if (is_array($arr2)) {
                    $arr = $this->getList($v['purview_id'], $arr);
                }
            }
        }
        return $arr;
    }

    /**
     * 在管理员组设置权限时显示
     */
    public function showList() {
        $arr = $this->where(Array('parent_id' => 0, 'is_enable' => 1))->field('purview_id,purview_name')->order('order_id asc')->select();
        foreach ($arr as $k => $v) {
            $arr[$k]['sub'] = $this->where(Array('parent_id' => $v['purview_id'], 'is_enable' => 1))->field('purview_id,purview_name')->order('order_id asc')->select();
        }
        return $arr;
    }

    /**
     * 获取子类别列表
     * @param int $parent_id 父类别ID
     */
    public function getSub($parent_id) {
        return $this->where(Array('parent_id' => $parent_id))->order('order_id asc')->select();
    }

    /**
     * 获取用户组没有的权限
     * @param int $group_id 用户组ID
     */
    public function getNotPurviewStr($group_id) {
        //获取权限ID列表
        $AGObj = D('admin_group');
        $purview_id_list = trim($AGObj->getFieldByGroupId($group_id, 'purview_id_list'), ',');
        if ($purview_id_list != '') {
            $purview_strs = $this->where(array('check_str' => array('neq', ''), 'purview_id' => array('not in', $purview_id_list)))->field('check_str')->select();
            $purviews_new = array();
            foreach ($purview_strs as $v) {
                $purviews_new[] = $v['check_str'];
            }
            return $purviews_new;
        }
        return array();
    }

    /**
     * 根据控制器和操作判断是否无权限
     * @param string $url 操作地址 控制器/操作名 或者 指定参数
     * @param array $purviews 无权限列表
     * @return true表示无权限
     */
    public function checkByUrl($url, $purviews) {
        $url = strtolower($url);
        if (in_array($url, $purviews)) {
            return true;
        } else if (strpos($url, '/') > 0) {
            $url2 = substr($url, 0, strpos($url, '/') + 1);
            if (in_array($url2, $purviews)) {
                return true;
            }
        }
        return false;
    }

}
